import { ref } from 'vue';

// WebSocket连接状态枚举
enum WebSocketStatus {
  CONNECTING = 'connecting',
  OPEN = 'open',
  CLOSING = 'closing',
  CLOSED = 'closed'
}

// WebSocket服务类
class WebSocketService {
  private ws: WebSocket | null = null;
  private reconnectTimeout: NodeJS.Timeout | null = null;
  private readonly maxReconnectAttempts = 5;
  private reconnectAttempts = 0;
  public status = ref(WebSocketStatus.CLOSED);

  // 初始化连接
  connect(url: string) {
    if (this.status.value === WebSocketStatus.CONNECTING) return;

    this.status.value = WebSocketStatus.CONNECTING;
    this.ws = new WebSocket(url);

    this.ws.onopen = () => {
      this.status.value = WebSocketStatus.OPEN;
      this.reconnectAttempts = 0;
    };

    this.ws.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data);
        // 触发自定义消息事件（可扩展为事件总线）
        window.dispatchEvent(new CustomEvent('ws-message', { detail: message }));
      } catch (error) {
        console.error('WebSocket消息解析失败:', error);
      }
    };

    this.ws.onclose = (event) => {
      this.status.value = WebSocketStatus.CLOSED;
      console.log(`WebSocket连接关闭，代码: ${event.code}，原因: ${event.reason}`);
      if (!event.wasClean && this.reconnectAttempts < this.maxReconnectAttempts) {
        this.reconnectAttempts++;
        this.reconnectTimeout = setTimeout(() => this.connect(url), 1000 * this.reconnectAttempts);
      }
    };

    this.ws.onerror = (error) => {
      console.error('WebSocket错误:', error);
      this.ws?.close();
    };
  }

  // 发送消息
  send(message: object) {
    if (this.status.value === WebSocketStatus.OPEN && this.ws) {
      this.ws.send(JSON.stringify(message));
    } else {
      console.warn('无法发送消息：连接未打开');
    }
  }

  // 关闭连接
  close() {
    if (this.ws) {
      this.reconnectAttempts = this.maxReconnectAttempts;
      if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
      this.ws.close();
      this.ws = null;
    }
  }
}

// 导出单例服务
export const webSocketService = new WebSocketService();